<template>
  <div>
    <pt-search :params="params" :config="config" label-width="110px" @search="search"/>
    <pt-table :columns="columns" :dataSource="tableData"
      :options="options" :fetch="getTableList" :pagination="pagination" />
    <el-dialog title="订单信息" v-dialogDrag :visible.sync="dialogTableVisible" width="1000px">
      <order-msg :curOrderlist="curOrderlist" :loading="diyLoading" />
    </el-dialog>
    <el-dialog title="订单退款" v-dialogDrag :visible.sync="refundVisible" width="400px">
      <pt-table-loading v-show="diyLoading" />
      <el-form label-width="80px" :model="refund" ref="ruleForm" size="small">
        <el-form-item label="退款方式" style="margin-bottom: 0">退回至用户支付的账号</el-form-item>
        <el-form-item label="退款商品" style="margin-bottom: 0">
          <el-checkbox-group v-if="orderGoodsList.cartItems && orderGoodsList.cartItems.length" 
            v-model="refund.orderItemIdStr" size="mini" @change="handleChangeGoodsChoose" :disabled="false">
            <div v-for="item in orderGoodsList.cartItems" :key="item.id">
              <el-checkbox :label="item.id">{{item.goodsName}}&nbsp;&nbsp;&nbsp;&nbsp;x{{item.num}}</el-checkbox>
            </div>
          </el-checkbox-group>
          <div class="goods-item"><span>配送费</span><span>￥{{orderGoodsList.finalDeliveryFee || 0}}</span></div>
          <div class="goods-item">
            <el-checkbox v-model="checkAll" @change="handleChangeAll">全选</el-checkbox>
            <span class="smit">退款金额￥{{refundPrice || 0}}</span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="refundVisible = false">取消</el-button>
        <el-button type="primary" :loading="loadingSubMit" @click="submitForm('ruleForm')" size="small">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/orderList'
import orderMsg from './components/order-msg'
import usermsg from './components/user-msg'
import paymsg from './components/pay-msg'
import acction from '@/utils/acction'
export default {
  components: { orderMsg, usermsg, paymsg },
  data() {
    return {// 表单配置
      columns: [{
        label: '用户信息',  minWidth: 140, align: 'left', render: row => <usermsg userMsg={row} />
      },{
        prop: 'businessname', label: '商家名称', minWidth: 100, align: 'center'
      },{
        label: '支付信息', minWidth: 80, align: 'right', render: row => <paymsg payMsg={row} />
      },{
        prop: 'statstr', label: '订单状态', minWidth: 160, align: 'center'
      },{
        prop: 'ordercode', label: '订单号', minWidth: 100, align: 'center'
      },{
        prop: 'createtime', label: '下单时间', minWidth: 100, align: 'center'
      },{
        button: true, label: '操作', width: 120, fixed: 'right', align: 'right',
        group: [{ 
          name: '手动退款', style: { color: '#2196F3' }, isToggle: true, toggle: row => {
            if (row.paytime) {
              const time = new Date().getTime()
              const payTime = new Date(row.paytime.replace(/-/g, '/')).getTime() + (3600 * 24 * 1000)
              if (time < payTime && row.status === 8 && !row.refund) return true
              else return false
            } else {
              return false
            }
          }, type: 'text', onClick: row => this.handleClickRefund(row)
        },{ 
          name: '查看', type: 'text', onClick: row => this.handleClick(row.id)
        }]
      }],
      pagination: { total: 0, page: 0, size: 10, curPage: 1 }, // 分页
      options: { // 表单外观
        mutiSelect: false, //  多选则 mutiSelect
        index: false, // 显示序号
        loading: false, // 表格动画
        initTable: true // 是否一挂载就加载数据
      },
      tableData: [], //表单数据
      curOrderlist: {}, //修改 选择数据
      config: [{
        key: 'agentIds', type: 'agentList', label: '区域'
      },{
        key: 'businessname', type: 'input', label: '商家名称', placeholder: '请输入商家名称'
      },{ 
        key: 'usermobile', type: 'input', label: '手机号', placeholder: '请输入手机号'
      },{
        key: 'ordercode', type: 'input', label: '订单号', placeholder: '请输入订单号'
      },{ 
        key: 'selectOrderTime', type: 'select', label: '下单时间', option: [{
          label: '今天', id: '1'
        },{
          label: '昨天', id: '2'
        },{
          label: '近7天', id: '3' 
        },{ 
          label: '全部', id: '4'
        }]
      },{
        key: 'selectOrderStatus', type: 'select', label: '订单状态', option: [{
          label: '全部', id: '1'
        },{
          label: '待接单', id: '2'
        },{
          label: '进行中', id: '3'
        },{
          label: '已完成', id: '4'
        },{
          label: '已取消', id: '5'
        },{
          label: '超时完成', id: '6'
        },{ 
          label: '退款', id: '7'
        }]
      },{ 
        key: 'page', type: 'button', group: [{
          name: '查看', type: 'primary', onClick: () => { }
        },{
          name: '重置',  type: 'info', onClick: () => this.reset()
        }]
      }],
      params: {
        page: 0,
        size: 10,
        agentIds: [], //区域
        businessname: '', // 商家名称
        usermobile: '', // 用户手机号
        ordercode: '', // 订单号
        selectOrderTime: '', // 下单时间
        selectOrderStatus: '' // 订单状态
      },
      diyLoading: false, //自定义等待
      loadingSubMit: false, // 表单等待
      dialogTableVisible: false,
      refundVisible: false, // 退款弹窗
      refund: { // 操作退款的数据
        reason: '', // 退款原因
        orderItemIdStr: [], // 退款的商品
        orderId: null
      },
      refundPrice: null, // 退款金额
      checkAll: false, // 选中所有的商品
      orderGoodsList: {} // 商品详情
    };
  },
  filters: {
    capitalize(t1, t2, t3) { //商品名称
      let str = t1;
      if (t2) str += t2;
      if (t3) str += `(${t3})`
      return str;
    },
    subMoney(m1, m2) {
      if (m1 >= '0' && m2 >= '0') {
        return new acction(m1, m2).accSub()
      } else {
        return '0'
      }
    },
    getRefund(f, l) { // 计算可退金额
      return new acction(f || 0, l || 0).accSub()
    }
  },
  methods: {
    search() { // 搜索
      this.pagination.curPage = 1
      this.pagination.page = 0
      this.getTableList()
    },
    reset() { // 重置
      this.pagination.curPage = 1
      for (const key in this.params) {
        if (key === 'page') {
          this.pagination.page = 0
        } else if (key === 'size') {
          this.pagination.size = 10
        } else if (key === 'agentIds') {
          this.params[key] = []
        } else {
          this.params[key] = ''
        }
      }
      this.getTableList()
    },
    handleClick(id) { //查看/修改订单操作
      this.dialogTableVisible = !this.dialogTableVisible;
      this.diyLoading = true
      api.orderInfo({ id }).then(res => {
        this.diyLoading = false
        this.curOrderlist = res.data
      }).catch(() => {
        this.diyLoading = false
      })
    },
    handleClickRefund(row) { // 手动退款
      this.refund.orderItemIdStr = []
      this.refund.orderId = row.id
      this.refund.reason = ''
      this.orderGoodsList = {}
      this.checkAll = false
      this.refundPrice = null
      this.refundVisible = true
      this.getSellChildren(row.id)
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields()
      })
    },
    handleChangeAll(val) { // 全选所有的商品
      if (val) {
        this.refund.orderItemIdStr = this.orderGoodsList.cartItems.length ? this.orderGoodsList.cartItems.map(i => i.id) : []
      } else {
        this.refund.orderItemIdStr = []
      }
      this.getOrderPirce()
    },
    handleChangeGoodsChoose() { // 切换选中退款商品
      if (this.refund.orderItemIdStr.length === this.orderGoodsList.cartItems.length) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
      this.getOrderPirce()
    },
    getOrderPirce() { // 获取退款金额
      this.diyLoading = true
      api.applyRefundInfo({ orderId: this.refund.orderId, orderItemIdStr: this.refund.orderItemIdStr.join(',') }).then(res => {
        if (res.success) {
          this.refundPrice = res.data
        }
      }).finally(() => { this.diyLoading = false })
    },
    getSellChildren(orderId) { // 获取商品列表
      this.diyLoading = true
      api.getSellChildren({ orderId }).then(res => {
        if (res.success) {
          this.orderGoodsList = res.data
        }
      }).finally(() => { this.diyLoading = false })
    },
    submitForm(formName) { // 提交退款金额
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = {...this.refund }
          params.orderItemIdStr = params.orderItemIdStr.join(',')
          this.loadingSubMit = true
          api.initiativeRefund(params).then(res => {
            if (res.success) {
              this.refundVisible = false
              this.$message.success('退款成功！')
              this.getTableList()
            }
          }).finally(() => { this.loadingSubMit = false })
        }
      })
    },
    getTableList() { //获取订单数据
      this.options.loading = true
      const params = { ...this.params }
      params.page = this.pagination.page
      params.size = this.pagination.size
      params.agentIds = params.agentIds.length > 0 ? params.agentIds.join(',') : ''
      api.orderList(params).then(res => {
        if (res.success) {
          this.tableData = res.data.list
          this.pagination.total = res.data.total
        }
      }).finally(() => { this.options.loading = false })
    }
  }
}
</script>
<style scoped>
  @import "/css/check.css";
</style>
